package com.crazy.shell.service.company;

import com.alibaba.fastjson.JSON;
import com.crazy.shell.common.exception.ServiceException;
import com.crazy.shell.common.persistent.dao.criteria.Criteria;
import com.crazy.shell.common.persistent.dao.entity.Example;
import com.crazy.shell.common.persistent.dao.mapper.Mapper;
import com.crazy.shell.common.persistent.service.BaseService;
import com.crazy.shell.common.persistent.service.impl.BaseServiceImpl;
import com.crazy.shell.common.redis.RedisClientTemplate;
import com.crazy.shell.dao.bean.BaseEnum;
import com.crazy.shell.dao.bean.CacheConstants;
import com.crazy.shell.dao.entity.Company;
import com.crazy.shell.dao.entity.Guest;
import com.crazy.shell.dao.entity.Users;
import com.crazy.shell.dao.mapper.mybatis.CompanyMapper;
import com.crazy.shell.dao.mapper.mybatis.UsersMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.MessageFormat;

/**
 * shell-crm
 * 创建人 : creazier.huang
 * 创建时间 : 16/7/7.
 */
@Component
public class CompanyServiceImpl extends BaseServiceImpl<Company>  implements CompanyService {

    private static final Logger logger = LoggerFactory.getLogger(CompanyServiceImpl.class);

    @Resource
    private CompanyMapper companyMapper;
    @Override
    public Mapper<Company> getMapper() {
        return companyMapper;
    }
    @Resource
    public RedisClientTemplate redisTemp;

    @Override
    public int countByObj(Company company) {
        int count = companyMapper.selectCountByExample(getExample(company));
        return count;
    }

    @Override
    public Company getFromCache (Integer uid) {
        String key = MessageFormat.format(CacheConstants.CACHE_COMPANY,uid);
        if(redisTemp.exists(key)){
            String json = redisTemp.get(key);
            return JSON.parseObject(json,Company.class);
        }

        Company cfg = new Company();
        cfg.setId(uid);
        cfg.setEnable(BaseEnum.EnableEnum.Enable.getKey());
        Company tar = this.getByObj(cfg);
        if(tar == null){
            throw new ServiceException("not find users by uid : "+ uid);
        }
        String reVal = redisTemp.set(key,JSON.toJSONString(tar));
        return tar;
    }


    private Example getExample(Company company){
        Example example = new Example(Users.class);
        Criteria criteria = example.createCriteria();
        if(StringUtils.isNotEmpty(company.getName()))
            criteria.andEqualTo("name",company.getName());

        return example;

    }



}
